# -*- coding: utf-8 -*-
from google.appengine.api import memcache
from django.conf import settings
from django.http import HttpResponse
from waveapi import robot
from waveapi import appengine_robot_runner
from djapp import controller
from djapp import models
from djapp import views
import passwords, logging


def get_inline_blip_id(json_reply):
    blip_id = None
    for data in json_reply:
        try:
            blip_id = data['data']['newBlipId']
            break
        except (KeyError, ValueError):
            continue
    return blip_id

def initialization(request):
    #message = "Access denied."
    #if request.user.is_authenticated():
        c = controller.Controller()
        level = c.get_level_dict()
        catalog_list = c.get_user_categories()
        myrobot = robot.Robot(passwords.ROBOT_NAME,
                              image_url = passwords.IMAGE_URL,
                              profile_url = passwords.PROFILE_URL)
        myrobot.setup_oauth(passwords.CONSUMER_KEY, passwords.CONSUMER_SECRET, 
                            server_rpc_base='http://www-opensocial.googleusercontent.com/api/rpc')
        appengine_robot_runner.run(myrobot)
        path = [None for i in level]
        for i in catalog_list:
            edited_wave = myrobot.fetch_wavelet(wave_id = catalog_list[i]['wave_id'].strip())
            blip = edited_wave.root_blip
            blip.all().delete()
            blip.append(catalog_list[i]['header'] + '\n')
            """
            annotation = []
            text1 = '\n' + catalog_list[i]['header']
            text2 = u'\n\n\nПрочие'
            logging.info("blip cleared. length: %d" % len(blip.text))
            blip.at(0).insert(text1+text2)
            #logging.info("text1 appended: %d" % len(blip.text))
            #blip.at(len(blip.text) - 1).insert(text2)
            #logging.info("text2 appended: %d" % len(blip.text))
            pos = len(blip.text)
            blip.insert_inline_blip(pos)
            logging.info("inlineblip inserted: %d" % pos)
            logging.info("adding range 100.other: %d, %d" % (len(blip.text) - len(text2)+2, pos))
            logging.info("adding range BOLD: %d, %d" % (len(text1) + 2, pos))
            annotation.append({'value': ('conv/title', catalog_list[i]['header']), 
                               'range': (0, len(text1)+1)})
            annotation.append({'value': ("style/fontWeight", "bold"), 
                               'range': (len(blip.text) - len(text2) + 2, pos)})
            annotation.append({'value': ('level', '100.other'), 
                               'range': (len(blip.text) - len(text2) + 1, pos)})
            for new_ann in annotation:
                blip.range(new_ann['range'][0], new_ann['range'][1]).annotate(new_ann['value'][0], new_ann['value'][1])
            json = myrobot.submit(edited_wave)
            new_blip_id = get_inline_blip_id(json)
            cat = models.Catalog.objects.create(path = path, name = 'other', 
                          wave_id = catalog_list[i]['wave_id'], blip_id = new_blip_id)
            #at.save() 
            edited_wave = myrobot.fetch_wavelet(wave_id = catalog_list[i]['wave_id'].strip())  
            blip = edited_wave.blips.get(cat.blip_id)
            blip.at(0).insert('\n\n')
            logging.info("root_blip annotation: %s, len: %d, text:\'%s\'" % (edited_wave.root_blip.annotations.serialize(), len(edited_wave.root_blip), edited_wave.root_blip.text))
            """
            myrobot.submit(edited_wave)
            message = "Done."
            return HttpResponse('<h1>'+message+'</h1>') 

def initialization_wtf(request):
    message = "Access denied."
    view = memcache.get("view") 
    if True:
        c = controller.Controller()
        cat = c.get_user_categories()
        lvl = c.get_level_dict()
        extended_tag_dict = c.get_extended_tag_dict()
        view = views.View()
        if not memcache.add("view", view, 600):
            memcache.set("view", view, 600)
            logging.error("Memcache [view] add failed.")
    begin = memcache.get("begin")
    if not begin:        
        wave_list = models.Wave.objects.all().order_by('id')
        if wave_list:
            begin =  wave_list[0].id
            if type(begin) == int:
                begin -= 1
            elif type(begin) == str or type(begin) == unicode:
                begin = begin[:-1]           
    if begin:
        logging.info("begin: %s" % begin)
        view.add_waves(begin, lvl, cat, extended_tag_dict)    
    else:
        logging.info("NO BEGIN!")
    return HttpResponse('<h1>'+message+'</h1>') 